package com.baosight.risk.common.quartz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baosight.risk.api.fltd.FltdProcessService;
import com.baosight.risk.api.riwa.RiwaEhrContractService;
import com.baosight.risk.api.zbaa.IZbaaTargetService;
import com.baosight.risk.common.aspects.factory.AsyncFactory;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.manager.AsyncManager;
import com.baosight.risk.common.utils.*;
import com.baosight.risk.mapper.riwa.RiwaEhrContractMapper;
import com.baosight.risk.mapper.zbaa.ZbaaTargetValueMapper;
import com.baosight.risk.service.riwa.entity.RiwaEhrContract;
import com.baosight.risk.service.riwa.entity.RiwaEhrContractValue;
import com.baosight.risk.service.system.entity.SysOperLog;
import com.baosight.risk.service.zbaa.entity.ZbaaTarget;
import com.baosight.risk.service.zbaa.entity.ZbaaTargetValue;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.security.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.Year;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Liuhaonan
 * @date 2020年 04月27日
 * @describe ehr协力系统合同考核扣分数据接口相关
 */
@Slf4j
@Component("riwaEhrTask")
public class RiwaEhrTask {
    @Autowired
    RiwaEhrContractMapper riwaEhrContractMapper;
    @Autowired
    private FltdProcessService fltdProcessService;
    @Autowired
    RiwaEhrContractService riwaEhrContractService;
    @Autowired
    ZbaaTargetValueMapper zbaaTargetValueMapper;
    @Autowired
    private IZbaaTargetService targetService;

    /**
     * 接口请求地址
     */
    private final String URL = ReadProperties.getValueString("riwaEhrContract.url");

    //获取ehr合同考核数据
    public void testParams(String params, String jobId) throws Exception {
        getDataByDay(params, jobId);
    }


    public void getDataByDay(String params, String jobId) throws Exception{
        // 系统代码
        String sysCode = "JV";
        // 密钥
        String key = "CONTRACT_INFO";
        // 秘钥+年月日
        key = key + getYYYYMMDD();
        String auCode = md5(sysCode, key);
        // (new MD5Utils()).verify(sysCode, key, auCode);
        // (new MD5Utils()).verify(sysCode, auCode);
        //日志
        List<SysOperLog> logs = new ArrayList<>();
        Exception error = null;

        try {
            //获取表里所有ehr数据
            RiwaEhrContract search = new RiwaEhrContract();
            List<RiwaEhrContract> allList = riwaEhrContractMapper.getEhrContractList(search);
            String resultData = null;
            //获取ehr接数据
            try {
                //这里range=W  一周的数据
                String getUrl = URL + "?sysCode="+ sysCode + "&auCode=" + auCode + "&range=A";
                resultData = HttpUtils.sendGet(getUrl);
                if (StringUtils.isEmpty(resultData)) throw new Exception("获取ehr协力系统合同考核扣分数据异常！接口返回："+resultData);
                // 解析接口返回
                List<RiwaEhrContract> targetValueList = handleData(resultData, allList);

            } catch (Exception e) {
                log.error("获取ehr协力系统合同考核扣分数据异常！接口返回："+resultData+"，异常信息："+e.getMessage());
            }

            logs.add(fltdProcessService.getLog("获取ehr协力系统合同考核扣分数据定时任务执行成功", 0, "", jobId));
        }catch (Exception e){
            error = e;
            log.error("获取ehr协力系统合同考核扣分数据异常！");
            logs.add(fltdProcessService.getLog("获取ehr协力系统合同考核扣分数据定时任务执行失败", 1, e.getMessage(), jobId));
        }


        // 保存日志到数据库
        AsyncManager.me().execute(AsyncFactory.batchRecordOper(logs));
        if (error != null) {
            throw error;
        }
    }

    /**
     * 处理接口返回数据,筛选去重数据
     * @param resultData
     * @param allList
     * @return
     */
    private List<RiwaEhrContract> handleData(String resultData, List<RiwaEhrContract> allList) {
        //处理后数据（仅插入可以对应到sourceTargetNo的数据）
        List<RiwaEhrContract> resultList = new ArrayList<>();
        try {
            JSONObject jsonObject = JSONObject.parseObject(resultData);
            String code = jsonObject.getString("code");
            if ("200".equals(code)) {
                JSONArray data = jsonObject.getJSONArray("data");
                List<RiwaEhrContractValue> list = JSONObject.parseArray(data.toJSONString(), RiwaEhrContractValue.class);
                //判断表里最后一条数据是否是当前日期的上个季度的数据
                String lastQuarter = getlastQuarter();
                double sumEvalScore = 0;
                for (RiwaEhrContract riwaEhrContract :allList){
                    if (!riwaEhrContract.getPeriodNo().equals(lastQuarter)){
                        String[] lastQuarterAboutMonth = getLastQuarterAboutMonth(lastQuarter);
                        for (int j =0;j<lastQuarterAboutMonth.length;j++){
                            for (RiwaEhrContractValue value :list){
                                if (value.getSettleYearMon().equals(lastQuarterAboutMonth[j])){
                                    sumEvalScore+= Double.parseDouble(value.getEvalScore());
                                }
                            }
                        }
                    }
                }

                String score = calculateProfit(sumEvalScore/3);
                ZbaaTarget search = new ZbaaTarget();
                search.setId("BXA021");
                ZbaaTarget target = targetService.get("BXA021");
                ZbaaTargetValue zbaaTargetValue = new ZbaaTargetValue();
                BeanUtils.copyBeanProp(zbaaTargetValue,target);
                BeanUtils.initBean(zbaaTargetValue);
                BeanUtils.initExt(zbaaTargetValue);
                zbaaTargetValue.setTargetValue(score);
                zbaaTargetValue.setPeriodNo(lastQuarter);
                zbaaTargetValue.setAcctYear(lastQuarter.substring(0,4));
                zbaaTargetValue.setId(IDGenerator.getIdStr());

            }
        }catch (Exception e) {
            log.error("获取ehr协力系统合同考核扣分数异常："+e.getMessage());
            e.printStackTrace();
        }
        return resultList;
    }

    /**
     * 获取当前年月日
     * @return
     */
    private static String getYYYYMMDD() {
        return new SimpleDateFormat("yyyyMMdd").format(new Date());
    }

    /**
     * 带秘钥加密
     *
     * @param text 明文
     * @param key 密钥
     * @return 密文
     */
    public static String md5(String text, String key) {
        try {
            return DigestUtils.md5Hex(text + key);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("md5加密失败");
        }
        return null;
    }

    /**
     * 判断是否日期属于上个季度
     * @param date
     * @return
     */
    public Boolean checkQuarter(String date){
        Date nowDate = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
        //当前日期
        String nowFormat = formatter.format(nowDate);
        nowFormat = nowFormat.substring(0,4) + nowFormat.substring(5,7);
        int nowYear = Integer.parseInt(nowFormat.substring(0, 4));
        //进来的数据年份
        int taskYear = Integer.parseInt(date.substring(0, 4));
        int lastYear = nowYear - 1;

        if (taskYear == nowYear || taskYear == lastYear){
            //取当前月份和数据月份
            String substring = date.substring(5);
            int nMonth = 0;
            int tMonth = 0;
            try {
                nMonth = Integer.parseInt(nowFormat.substring(5));
                tMonth = Integer.parseInt(date.substring(5));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

            //判断当前日期
            //第二季度
            if (nMonth >= 4 && nMonth <= 6){
                //先判断是否和当年为同一年,在判断是否为当前时间的上个季度
                if (taskYear != nowYear){
                    return false;
                }else {
                    if (tMonth >= 1 && tMonth <= 3){
                        return true;
                    }else return false;
                }
            }else if (nMonth > 6 && nMonth < 10){//第三季度
                if (taskYear != nowYear){
                    return false;
                }else {
                    if (tMonth >= 4 && tMonth <= 6){
                        return true;
                    }else return false;
                }
            }else if (nMonth > 9 && nMonth < 13){//第四季度
                if (taskYear != nowYear){
                    return false;
                }else {
                    if (tMonth >= 7 && tMonth <= 9){
                        return true;
                    }else return false;
                }
            }else {//第一季度
                if (taskYear != nowYear - 1 ){
                    return false;
                }else {
                    if (tMonth >= 10 && tMonth <= 12){
                        return true;
                    }else return false;
                }
            }
        }
        return false;
    }

    public static String calculateProfit(double doubleValue) {
        // 保留4位小数
        DecimalFormat df = new DecimalFormat("0.0000");
        String result = df.format(doubleValue);
        // 获取小数 . 号第一次出现的位置
        int index = firstIndexOf(result, ".");
        // 字符串截断
        return result.substring(0, index + 3);
    }

    public static int firstIndexOf(String str, String pattern) {
        for (int i = 0; i < (str.length() - pattern.length()); i++) {
            int j = 0;
            while (j < pattern.length()) {
                if (str.charAt(i + j) != pattern.charAt(j))
                    break;
                j++;
            }
            if (j == pattern.length())
                return i;
        }
        return -1;
    }

    /**
     * @param periodNo 周期
     * @return
     * @description 描述
     * @author CuiShiHao
     */
    public String dealQuarter(String periodNo) {
        String year = periodNo.substring(0, 4);
        String month = periodNo.substring(4, 6);
        String result = "";
        switch (month) {
            case "01":
            case "02":
            case "03":
                result = "Q1";
                break;
            case "04":
            case "05":
            case "06":
                result = "Q2";
                break;
            case "07":
            case "08":
            case "09":
                result = "Q3";
                break;
            case "10":
            case "11":
            case "12":
                result = "Q4";
                break;
        }
        return year + result;
    }

    /**
     * 判断表里取出来的数据是否是当前日期上个季度的
     * @param periodNo
     * @return
     */
    public Boolean checkQ(String periodNo) {
        //算出当前日期的上个季度
        Date nowDate = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
        //当前日期
        String nowFormat = formatter.format(nowDate);
        nowFormat = nowFormat.substring(0,4) + nowFormat.substring(5,7);

        String nowYear = nowFormat.substring(0, 4);
        String nowMonth = nowFormat.substring(4, 6);
        String lastQuarter = "";
        switch (nowMonth) {
            case "01":
            case "02":
            case "03":
                lastQuarter = "Q4";
                nowYear = (Integer.parseInt(nowYear) - 1) + "";
                break;
            case "04":
            case "05":
            case "06":
                lastQuarter = "Q1";
                break;
            case "07":
            case "08":
            case "09":
                lastQuarter = "Q2";
                break;
            case "10":
            case "11":
            case "12":
                lastQuarter = "Q3";
                break;
        }
//        String taskYear = periodNo.substring(0, 4);
//        String taskQuarter = periodNo.substring(4, 6);

        return periodNo.equals(nowYear+lastQuarter);
    }

    /**
     * 求出当前日期上个季度的字符串
     * @param
     * @return
     */
    public String getlastQuarter() {
        //算出当前日期的上个季度
        Date nowDate = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
        //当前日期
        String nowFormat = formatter.format(nowDate);
        nowFormat = nowFormat.substring(0,4) + nowFormat.substring(5,7);

        String nowYear = nowFormat.substring(0, 4);
        String nowMonth = nowFormat.substring(4, 6);

//        nowYear = "2020";
//        nowMonth = "04";
        String lastQuarter = "";
        switch (nowMonth) {
            case "01":
            case "02":
            case "03":
                lastQuarter = "Q4";
                nowYear = (Integer.parseInt(nowYear) - 1) + "";
                break;
            case "04":
            case "05":
            case "06":
                lastQuarter = "Q1";
                break;
            case "07":
            case "08":
            case "09":
                lastQuarter = "Q2";
                break;
            case "10":
            case "11":
            case "12":
                lastQuarter = "Q3";
                break;
        }
//        String taskYear = periodNo.substring(0, 4);
//        String taskQuarter = periodNo.substring(4, 6);

        return nowYear+lastQuarter;
    }

    public String[] getLastQuarterAboutMonth(String lastQuarter){
        String quarter = lastQuarter.substring(5, 6);
        String year = lastQuarter.substring(0, 4);
        switch (quarter) {
            case "1":
                return new String[]{year+"01",year+"02",year+"03"};
            case "2":
                return new String[]{year+"04",year+"05",year+"06"};
            case "3":
                return new String[]{year+"07",year+"08",year+"09"};
            case "4":
                return new String[]{year+"10",year+"11",year+"12"};
        }
        return null;
    }



}
